﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace EbookCopier
{
    /// <summary>
    /// Cmder 管理器，这一方案类似于插件的实现。
    /// </summary>
    public class CmderManager
    {
        static List<Type> cmderTypes = null;
        static CmderManager()
        {
            cmderTypes = new List<Type>();
            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (type.IsSubclassOf(typeof(Cmder)) && !type.IsAbstract)
                {//从Cmder继承，且可以实例化
                    cmderTypes.Add(type);
                }
            }
        }
        /// <summary>
        /// 获取加载的 Cmder名称的集合。
        /// </summary>
        /// <returns></returns>
        public static string[] GetCmderNames()
        {
            List<string> names = new List<string>();
            foreach (Type type in cmderTypes)
            {
                CmderAttribute attr = Attribute.GetCustomAttribute(type, typeof(CmderAttribute)) as CmderAttribute;
                if (attr != null)
                    names.Add(attr.Name);
            }

            return names.ToArray();
        }
        /// <summary>
        /// 通过名称查找 Cmder。
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static Type GetCmderByName(string name)
        {
            Type result = null;
            foreach (Type type in cmderTypes)
            {
                CmderAttribute attr = Attribute.GetCustomAttribute(type, typeof(CmderAttribute)) as CmderAttribute;
                if (attr != null && attr.Name == name)
                {
                    result = type;
                    break;
                }
            }

            return result;
        }
        /// <summary>
        /// 通过名称查找 Cmder。
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static CmderAttribute GetCmderAttributeByName(string name)
        {
            CmderAttribute result = null;
            foreach (Type type in cmderTypes)
            {
                CmderAttribute attr = Attribute.GetCustomAttribute(type, typeof(CmderAttribute)) as CmderAttribute;
                if (attr != null && attr.Name == name)
                {
                    result = attr;
                    break;
                }
            }

            return result;
        }
    }
}
